package cn.edu.swu.core;

import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public abstract class AbstractRepo {


    private static BasicDataSource dataSource;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException e){
            throw new RuntimeException(e);
        }
        dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/bookstore");
        dataSource.setUsername("root");
        dataSource.setPassword("660941217tml");

        dataSource.setMinIdle(5);
        dataSource.setMaxIdle(10);
        dataSource.setMaxTotal(20);
        dataSource.setInitialSize(5);
    }


    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public void query(String sql,ResultSetVisitor visitor) throws SQLException {
        try (Connection connection = getConnection()){
            try (Statement statement = connection.createStatement()){
                ResultSet resultSet = statement.executeQuery(sql);
                while (resultSet.next()){
                    visitor.visit(resultSet);
                }
            }

        }
    }


    public void execute(String sql) throws SQLException {
        try (Connection connection = getConnection()){
            try (Statement statement = connection.createStatement()){
                statement.execute(sql);

                }
            }

        }
    }



